package com.sun.temp.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sun.temp.bean.FilePath;
import com.sun.temp.bean.Material;
import com.sun.temp.common.result.Result;
//import com.sun.temp.netty.NettyClient;
//import com.sun.temp.netty.NettyManager;
import com.sun.temp.service.FilePathService;
import com.sun.temp.service.MaterialService;
//import com.sun.temp.task.MyRunnable;
import com.sun.temp.utils.PLCUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
//import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.krb5.internal.NetClient;

import static java.lang.Thread.sleep;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ScheduledFuture;

@Slf4j
@RestController
@RequestMapping("/quartz/task")
public class TaskController {

    @Resource
//    private ThreadPoolTaskScheduler threadPoolTaskScheduler;
//    @Resource
//    private NettyClient nettyClient;
//    @Resource
//    private NettyManager nettyManager;

    @Autowired
    private FilePathService filePathService;

    @Autowired
    private MaterialService materialService;

    private ScheduledFuture future;

    /**
     * 复位
     * @return
     */
    @GetMapping("/reset")
    public Result reset() throws Exception  {

        //如果库里有状态为1的数据，改为已失效状态3
        List<Material> list = materialService.queryMaterialByStatus(1);
        if(list.size() > 0){
            for (Material m : list){
                if(m.getStatus() == 1){
                    m.setStatus(3);
                }
            }
            materialService.updateBatchById(list);
        }
        //复位
        PLCUtil.writeInt16("VW1000", 3);
        sleep(2000);
        //归0
        PLCUtil.writeInt16("VW1000", 0);
        return Result.success(true);
    }

    /**
     * 开启定时任务
     */
    @GetMapping("/startTask")
    public Result startTask() throws Exception  {
        // 复位
        PLCUtil.writeInt16("VW1000", 3);
        sleep(3000);
        // 归零
        PLCUtil.writeInt16("VW1000", 0);
        sleep(3000);
        // 发送VW1000 为1-上位机发送启动
        PLCUtil.writeInt16("VW1000", 1);
        log.info("为1-上位机发送启动");

        // 启动定时任务
//        future = threadPoolTaskScheduler.schedule(new MyRunnable(), new Trigger() {
//            @Override
//            public Date nextExecutionTime(TriggerContext triggerContext) {
//                return new CronTrigger("*/5 * * * * ?").nextExecutionTime(triggerContext);
//            }
//        });

        return Result.success(true);
    }


    /**
     * 关闭定时任务
     * @return
     */
    @GetMapping("/stopTask")
    public Result stopTask() throws Exception{
        if (future != null) {
            future.cancel(true);
            future = null;
        }

        //复位
//        PLCUtil.writeInt16("VW1000", 3);
//        sleep(2000);
//        //归0
//        PLCUtil.writeInt16("VW1000", 0);

//        //如果库里有状态为1的数据，异常操作产生的，改为已失效状态3
//        List<Material> list = materialService.queryMaterialByStatus(1);
//        if(list.size() > 0){
//            for (Material m : list){
//                if(m.getStatus() == 1){
//                    m.setStatus(3);
//                }
//            }
//            materialService.updateBatchById(list);
//        }

        return Result.success(true);
    }

    /**
     * 查询定时任务状态true执行中，false已关闭
     * @return
     */
    @GetMapping("/getState")
    public Result getState() {
        if (future != null) {
            return Result.success(true);
        }else{
            return Result.success(false);
        }
    }


    /**
     * 脚本测试
     * @return
     * @throws Exception
     */
    @GetMapping("/pythonTest")
    public Result pythonTest() throws Exception{
//        needlePress();
        needleMove();
        return Result.success(true);
    }

    /**
     * 测试--顶针上升move
     * @return
     * @throws Exception
     */
    public Result needleMove() throws Exception{

        // Python脚本路径及参数
        String pythonScript = "D:\\zydm\\code\\sumimoto-rob\\doc\\needleMove.py";
        pythnExcute(pythonScript);
        return Result.success();
    }

    /**
     * 测试--start开始加热
     * @return
     * @throws Exception
     */
    public Result startHeating() throws Exception {

        // Python脚本路径及参数
        String pythonScript = "D:\\zydm\\code\\sumimoto-rob\\doc\\startHeating.py";
        pythnExcute(pythonScript);
        return Result.success();
    }

    public void pythnExcute(String path) throws Exception{
        ProcessBuilder processBuilder = new ProcessBuilder("python", path);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;

        while ((line = reader.readLine()) != null) {
            System.out.printf(line);
            output.append(line).append("\n");
        }

        int exitCode = -1;
        try {
            exitCode = process.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (exitCode == 0) {
                System.out.println("Python脚本成功运行！输出结果为:\n" + output.toString());
            } else {
                System.err.println("Python脚本运行失败！退出码为:" + exitCode);
            }

            process.destroy();
        }
    }

}